package org.nobody.mallb2c.mallproduct.app;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.nobody.mallb2c.mallproduct.entity.CategoryEntity;
import org.nobody.mallb2c.mallproduct.service.CategoryService;
import org.nobody.common.utils.R;


/**
 * 商品三级分类
 *
 * @author fancier
 * @email fancier2093@gmail.com
 * @date 2020-07-30 16:25:27
 */
@RestController
@RequestMapping("mallproduct/category")
public class CategoryController {
  @Autowired
  private CategoryService categoryService;

  @GetMapping("parent/{parentId}")
  public R queryCategoriesByPid(@PathVariable("parentId")Long pid){
    QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
    // 如果pid为-1要查询所有
    if (pid != -1) {
      wrapper.eq("parent_id", pid);
    }
    List<CategoryEntity> categoryEntities = categoryService.list(wrapper);
    return R.ok().put("data", categoryEntities);
  }

  /**
   * 查出所有分类以及子分类,以树形结构组装起来
   */
  @RequestMapping("/list/tree")
  public R list() {
    List<CategoryEntity> entities = categoryService.listWithTree();

    return R.ok().put("data", entities);
  }


  /**
   * 信息
   */
  @RequestMapping("/info/{catId}")
  public R info(@PathVariable("catId") Long catId) {
    CategoryEntity category = categoryService.getById(catId);

    return R.ok().put("data", category);
  }

  /**
   * 保存
   */
  @RequestMapping("/save")
  public R save(@RequestBody CategoryEntity category) {
    categoryService.save(category);

    return R.ok();
  }

  /**
   * 排序
   */
  @RequestMapping("/update/sort")
  public R updateSort(@RequestBody CategoryEntity[] category) {
    categoryService.updateBatchById(Arrays.asList(category));

    return R.ok();
  }

  /**
   * 修改
   */
  @RequestMapping("/update")
  public R update(@RequestBody CategoryEntity category) {
    categoryService.updateCascade(category);

    return R.ok();
  }

  /**
   * 删除
   *
   * @RequestBody 需要获取请求体, 故必须发送post请求
   * SpringMVC自动将请求体的数据(json) 转为对应的对象
   */
  @RequestMapping("/delete")
  public R delete(@RequestBody Long[] ids) {
    categoryService.removeMenuByIds(Arrays.asList(ids));

    return R.ok();
  }

}
